package me.zhengjie.modules.enrstu.rest;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.enrstu.domain.ReviewInformation;
import me.zhengjie.modules.enrstu.service.AuditService;
import me.zhengjie.modules.enrstu.service.ReviewInformationService;
import me.zhengjie.modules.enrstu.service.dto.*;
import me.zhengjie.modules.system.domain.Dept;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.utils.SecurityUtils;
import me.zhengjie.utils.resp.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.security.Security;
import java.util.Arrays;
import java.util.List;


@RestController
@RequiredArgsConstructor
    @Api(tags = "招生系统:报名管理-审核")
@RequestMapping("/api/enrstu/audit")
public class AuditController {
    private static final Logger log = LoggerFactory.getLogger(AuditController.class);
    private final AuditService auditService;
    private final ReviewInformationService rwService;
    private final UserRepository userRepository;
    @GetMapping("/list/wait")
    @Log("获取待审核列表")
    @ApiOperation("获取待审核列表")
    @PreAuthorize("@el.check('audit:list') or @el.check('audit:review')")
    public ResponseEntity<Object> getPreliminaryWaitAudit(ReviewWaitInfoQueryCriteria resources, Pageable pageable){
        return new ResponseEntity<>( auditService.findReviewWaitInfoList(resources,pageable),HttpStatus.OK);
    }
    @GetMapping("/list/already")
    @Log("获取已审核列表")
    @ApiOperation("获取已审核列表")
    @PreAuthorize("@el.check('audit:list') or @el.check('audit:review')")
    public ResponseEntity<Object> getPreliminaryAlreadyAudit(ReviewAlreadyOrAcceptedInfoQueryCriteria resources, Pageable pageable){
        return new ResponseEntity<>(auditService.findReviewAlreadyInfoList(resources,pageable),HttpStatus.OK);
    }
    @GetMapping("/list/accepted")
    @Log("获取录取列表")
    @ApiOperation("获取录取列表")
    @PreAuthorize("@el.check('audit:list') or @el.check('audit:accepted')")
    public ResponseEntity<Object> getPreliminaryAcceptedAudit(ReviewAlreadyOrAcceptedInfoQueryCriteria resources, Pageable pageable){
        return new ResponseEntity<>(auditService.findReviewAcceptedInfoList(resources,pageable),HttpStatus.OK);
    }

    @GetMapping("/list/details/{childrenId}")
    @Log("获取列表详情")
    @ApiOperation("获取列表详情")
    @PreAuthorize("@el.check('audit:list')")
    public ResponseEntity<Object> getListDetails(@PathVariable String  childrenId){
        return new ResponseEntity<>( auditService.getListDetails(childrenId),HttpStatus.OK);
    }

    @GetMapping("/rw/dynamicsDetails")
    @Log("动态获取待审核详情列表详情")
    @ApiOperation("动态获取待审核详情列表详情")
    @PreAuthorize("@el.check('audit:list')")
    public ResponseEntity<Object> getRwDynamicsListDetails(Boolean isRepeatedReview){
        //1.获取待初审审核列表
        Long dept = auditService.getUserInfo().getDept().getId();
        //2.获取待复审审核列表,最早提交的审核记录
        return new ResponseEntity<>( rwService.findRwDynamicsList(dept,isRepeatedReview),HttpStatus.OK);
    }
    @GetMapping("/ra/dynamicsDetails")
    @Log("动态获取已审核详情列表详情")
    @ApiOperation("动态获取已审核详情列表详情")
    @PreAuthorize("@el.check('audit:list')")
    public ResponseEntity<Object> getRaDynamicsListDetails(){
//        return new ResponseEntity<>( auditService.getDynamicsListDetails(),HttpStatus.OK);
        return null;

    }
    @GetMapping("/rac/dynamicsDetails")
    @Log("动态获取录取列表详情")
    @ApiOperation("动态获取录取列表详情")
    @PreAuthorize("@el.check('audit:list')")
    public ResponseEntity<Object> getRacDynamicsListDetails(){
//        return new ResponseEntity<>( auditService.getDynamicsListDetails(),HttpStatus.OK);
        return null;

    }
    @GetMapping("/file/download")
    @Log("下载附件信息")
    @ApiOperation("下载附件信息")
    @PreAuthorize("@el.check('audit:download')")
    public ResponseEntity<StreamingResponseBody> downloadFile(@RequestBody List<String> linkIds) {

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=download.zip");

        return ResponseEntity.ok()
                .headers(headers)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(out -> {
                    try (InputStream is = new java.io.ByteArrayInputStream(auditService.fileDownload(linkIds))) {
                        byte[] buffer = new byte[4096];
                        int bytesRead;
                        while ((bytesRead = is.read(buffer)) != -1) {
                            out.write(buffer, 0, bytesRead);
                        }
                    } catch (Exception e) {
                        throw new RuntimeException("Failed to write file to response", e);
                    }
                });
    }

    @PutMapping("/review")
    @Log("审核处理")
    @ApiOperation("审核处理")
    @PreAuthorize("@el.check('audit:review')")
    public ResponseEntity<Object> review( @RequestBody ReviewOrAcceptedHandler reviewHandler){
        auditService.review(reviewHandler);
        return new ResponseEntity<>(Result.ok(),HttpStatus.OK);
    }

    @PutMapping("/accepted")
    @Log("录取处理")
    @ApiOperation("录取处理")
    @PreAuthorize("@el.check('audit:accepted')")
    public ResponseEntity<Object> accepted( @RequestBody List<ReviewOrAcceptedHandler> acceptedHandler){
        //转为list
        auditService.accepted(acceptedHandler);
        return new ResponseEntity<>(Result.ok(),HttpStatus.OK);
    }
    @Log("录取列表导出数据")
    @ApiOperation("录取列表导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('audit:download') or @el.check('audit:accepted')")
    public void exportSchool(HttpServletResponse response) throws IOException {
        auditService.download(response);
    }

}
